﻿
using System;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using ICSharpCode.SharpZipLib.Checksum;

namespace CardRegisterCollection.Utility
{
    /// <summary>
    /// 压缩包帮助类
    /// </summary>
    public class ZipUtility
    {
        public static void Create(string sourceDirectory, string destinationZipFile, string password)
        {
            var fz = new FastZip
            {
                CreateEmptyDirectories = true
            };
            if (!string.IsNullOrWhiteSpace(password))
                fz.Password = password;
            fz.CreateZip(destinationZipFile, sourceDirectory, true, "");
        }

        public static void UnZip(string sourceZipFile, string destinationDirectory, string password)
        {
            if (!Directory.Exists(destinationDirectory))
                Directory.CreateDirectory(destinationDirectory);

            var stream = new ZipInputStream(File.OpenRead(sourceZipFile.Trim()));
            stream.Password = password;


            FileStream fs = null;
            ZipEntry entry = null;
            while ((entry = stream.GetNextEntry()) != null)
            {
                if (!string.IsNullOrEmpty(entry.Name))
                {
                    var fileName = Path.Combine(destinationDirectory, entry.Name);
                    fileName = fileName.Replace('/', '\\');

                    var fileDirectoryName = Path.GetDirectoryName(fileName);
                    if (!string.IsNullOrWhiteSpace(fileDirectoryName) && !Directory.Exists(fileDirectoryName))
                    {
                        Directory.CreateDirectory(fileDirectoryName);
                    }

                    fs = File.Create(fileName);
                    var size = 2048;
                    var data = new byte[size];
                    while (true)
                    {
                        size = stream.Read(data, 0, data.Length);
                        if (size > 0)
                            fs.Write(data, 0, data.Length);
                        else
                            break;
                    }
                    fs?.Close();
                }
            }
            stream.Dispose();
            stream.Close();
        }


        #region 删除文件夹
        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="dir">文件夹路径</param>
        public static void DeleteFolder(string dir)
        {
            if (!Directory.Exists(dir)) //如果存在这个文件夹删除之
            {
                return;
            }
            foreach (var d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                    File.Delete(d); //直接删除其中的文件
                else
                    DeleteFolder(d); //递归删除子文件夹
            }
            Directory.Delete(dir, true); //删除已空文件夹

        }
        #endregion
    }
}
